package com.azhon.blecs.client;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.azhon.blecs.R;
import com.azhon.blecs.server.ServerActivity;

/**
 * 项目名:    BleCS
 * 包名       com.azhon.blecs.client
 * 文件名:    ClientChatActivity
 * 创建时间:  2019/7/16 on 15:21
 * 描述:     TODO
 *
 * @author 阿钟
 */

public class ClientChatActivity extends AppCompatActivity {

    private static final String TAG = "ClientChatActivity";
    private DeviceModel device;
    private BluetoothGatt bluetoothGatt;
    private TextView tvLog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_chat);
        device = getIntent().getParcelableExtra("device");
        setTitle(device.getName());
        initView();
        //发起连接
        bluetoothGatt = device.getDevice().connectGatt(this, false, bluetoothGattCallback);
    }

    private void initView() {
        tvLog = findViewById(R.id.tv_log);
        final EditText etContent = findViewById(R.id.et_content);
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = etContent.getText().toString();
                if (TextUtils.isEmpty(s)) return;
                sendData(s);
                etContent.setText("");
            }
        });

    }

    private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.e(TAG, "onConnectionStateChange 连接成功");
                handler.sendMessage(handler.obtainMessage(0, "连接成功"));
                //查找服务
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_CONNECTING) {
                Log.e(TAG, "onConnectionStateChange 连接中......");
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.e(TAG, "onConnectionStateChange 连接断开");
                handler.sendMessage(handler.obtainMessage(0, "连接断开"));
            } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
                Log.e(TAG, "onConnectionStateChange 连接断开中......");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            //设置读特征值的监听，接收服务端发送的数据
            BluetoothGattService service = bluetoothGatt.getService(ServerActivity.UUID_SERVER);
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(ServerActivity.UUID_CHAR_READ);
            boolean b = bluetoothGatt.setCharacteristicNotification(characteristic, true);
            Log.e(TAG, "onServicesDiscovered 设置通知 " + b);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            String data = new String(characteristic.getValue());
            Log.e(TAG, "onCharacteristicChanged 接收到了数据 " + data);
            handler.sendMessage(handler.obtainMessage(1, data));
        }
    };

    /**
     * 发送数据
     *
     * @param msg
     */
    public void sendData(String msg) {
        if (bluetoothGatt == null) {
            return;
        }
        //找到服务
        BluetoothGattService service = bluetoothGatt.getService(ServerActivity.UUID_SERVER);
        if (service == null) {
            return;
        }
        //拿到写的特征值
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(ServerActivity.UUID_CHAR_WRITE);
        bluetoothGatt.setCharacteristicNotification(characteristic, true);
        characteristic.setValue(msg.getBytes());
        bluetoothGatt.writeCharacteristic(characteristic);
        Log.e(TAG, "sendData 发送数据成功");
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    setTitle(device.getName() + "（" + msg.obj + "）");
                    break;
                case 1:
                    tvLog.append(msg.obj + "\n");
                    break;
                default:
                    break;
            }
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
        }
    }
}
